package com.sjzs.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.sjzs.web.common.BaseAction;
import com.sjzs.web.dao.AttachDao;
import com.sjzs.web.po.Attach;
import com.sjzs.web.po.User00;

public class AttachAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private String uploadType; // 上传类型 000 上传安装包
	private String linkguid; // 上传关联GUID
	private File file;
	private String filename;	
	private AttachDao attachDao;
	private String devuid;	//用户id

	public String getDevuid() {
		return devuid;
	}
	public void setDevuid(String devuid) {
		this.devuid = devuid;
	}
	public AttachDao getAttachDao() {
		return attachDao;
	}
	public void setAttachDao(AttachDao attachDao) {
		this.attachDao = attachDao;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getUploadType() {
		return uploadType;
	}

	public void setUploadType(String uploadType) {
		this.uploadType = uploadType;
	}

	public String getLinkguid() {
		return linkguid;
	}

	public void setLinkguid(String linkguid) {
		this.linkguid = linkguid;
	}

	public String uploadAttach() throws IOException{		
		
		// 实现上传
		//基于myFile创建一个文件输入流  
        InputStream is = new FileInputStream(this.getFile());            
        // 设置上传文件目录  
        String uploadPath = ServletActionContext.getServletContext()  
                .getRealPath("/Products/" + this.getDevuid() + "/" + this.uploadType);             
        // 设置目标文件  
        File toFile = new File(uploadPath, this.getFilename());    
        if(!toFile.getParentFile().exists()){
        	toFile.getParentFile().mkdirs();
        }
        // 创建一个输出流  
        OutputStream os = new FileOutputStream(toFile);    
        //设置缓存  
        byte[] buffer = new byte[1024];    
        int length = 0;    
        //读取myFile文件输出到toFile文件中  
        while ((length = is.read(buffer)) > 0) {  
            os.write(buffer, 0, length);  
        }     
        //关闭输入流  
        is.close();            
        //关闭输出流  
        os.close();  
        //保存附件信息
        
        Attach attach = new Attach();
        attach.setUserid(this.getDevuid());
        attach.setLinkguid(linkguid);
        attach.setProductname(filename);
        attach.setProducttype(uploadType);
        attach.setSavepath("Products/" + this.getDevuid() + "/" + this.uploadType + "/" + this.filename);
        attachDao.saveAttach(attach);
		return SUCCESS;
	}
}
